<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>
			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container">
							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="上模人员:" @click="openBaseScreen('人员')"
											required>
											<u--input v-model="baseFormData.empolorName" placeholder="请选择上模人员" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">

										<u-form-item labelWidth="auto" label="上模开始时间:">
											<u--input v-model="baseFormData.StartTime" placeholder="自动带出开始时间" readonly
												border="none" /></u--input>
										</u-form-item>
									</u-col>

									<u-col span="4">

										<u-form-item labelWidth="auto" label="模具:" @click="openBaseScreen('模具')"
											required>
											<u--input v-model="baseFormData.MoldNO" placeholder="请选择模具名称" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>

								</u-row>


								<u-row justify="start" gutter="20">
									<u-col span="8">
										<u-form-item labelWidth="auto" label="产品:" @click="AddProductName" required>
											<u--input v-model="baseFormData.ProductName" placeholder="请选择产品" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">

										<u-form-item labelWidth="auto" label="设备名称:" required>
											<u--input v-model="baseFormData.EquipmentName" placeholder="请选择设备" readonly
												border="none"></u--input>

										</u-form-item>
									</u-col>
								</u-row>
								<u-row justify="start" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="库位" @click="openBaseScreen('库位')" required
											v-show="MoldParameter==0">
											<u--input v-model="baseFormData.FStorageName" placeholder="请选择库位" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>

								</u-row>
							</u--form>
						</view>
						<view class="table">
							<table>
								<tr>
									<th width="10%">序号</th>
									<th>保养项目</th>
									<th>检验项说明</th>
									<th width='25%'>保养结果</th>
								</tr>
								<tr v-for="(item, index) in tableData">
									<td>{{index + 1}}</td>
									<td>
										<u--textarea v-model="item.TypeName" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.InspectionRemark" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<uni-data-checkbox v-model="item.Result" :localdata="sexs" />
									</td>
								</tr>

							</table>

						</view>
					</view>


					<view class="bottomBtnsOne" v-show='ButtonShow'>
						<button block @click="submit" v-show="submitButtonShow">
							{{submitButton}}
						</button>
					</view>

				</view>
			</template>

		</st-mc-framework>

		<u-toast ref="uToast"></u-toast>
		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<u-action-sheet :actions="ProductNameList" :show="ProductNameShow" @select="ProductNameClick"
			@close="ProductNameClose"></u-action-sheet>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDate,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {

				ButtonShow: true,
				ProductNameList: [],
				ProductNameShow: false,
				showMLoading: false,
				loadingName: '正在加载中……',

				FormData: {
					MoldNO: '请选择模具名称',
					EquipmentName: '请选择设备',
					ProductName: '请选择产品'
				},
				baseFormData: {
					JobOrderID: null,
					EquipmentName: '',
					EquipmentID: '',
					empolorName: '',
					empolorID: null,
					StartTime: '',
					MoldNO: '',
					MoldID: '',
					ProductID: null,
					ProductName: '',
					FStorageID: null,
					FStorageName: '',
				},
				sexs: [{
					text: '合格',
					value: 0
				}, {
					text: '不合格',
					value: 1
				}],
				tableData: [],

				modalshow: false,
				modaltitle: '',
				modalcontent: '',
				submitButton: '提交',
				submitButtonShow: true,

				MoludList: [],
				ProductNameselect: false, //第一次进来是否多个
				FWorkshopID: null, //模块id
				ModuleTitle: '', //标题
				MoldParameter: null, //判断是否展示库位
			};
		},

		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName

			this.MoldStockParam();
			// 获取列表数据
			this.getList();
		},
		onLoad(item) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;

			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			// 主处理逻辑
			if (item.ZSChangeMoldID) {
				setLoading(true);
				this.queryList(item.ZSChangeMoldID);
				return;
			}
			// 处理调度项
			if (item.Dispatchitem) {
				setLoading(true);
				const dispatchItem = JSON.parse(item.Dispatchitem);
				console.log(dispatchItem);
				dispatchItem.EquipmentID = MesBasicInfo.warehouse.EquipmentID
				this.baseFormData = Object.assign(this.baseFormData, dispatchItem);
				console.log('ssss');
				this.getZS_getSMoldID('自动');
			}
			// 统一处理表单默认值
			const formDefaults = {
				EquipmentID: MesBasicInfo.warehouse.EquipmentID,
				EquipmentName: MesBasicInfo.warehouse.EquipmentName,
				StartTime: getFormatDate(new Date()),
				empolorName: UserInfo.EmplName,
				empolorID: UserInfo.EmplID
			};
			this.assignFormData(this.baseFormData, formDefaults);
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回 
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		onShow() {
			var that = this
			uni.$on('refreshDetail', (res) => {
				that.getValue(res.data); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshDetail');
		},
		methods: {
			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			MoldStockParam() {
				var that = this
				that.Request.request('getMoldStockParam', {}, function(res) {
					console.log(res);
					that.MoldParameter = res.data.ds[0].MoldParameter
				})
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			ProductNameClose() {
				if (this.ProductNameselect == false) {
					this.ProductNameShow = false
				}
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
				var parentData
				if (that.modaltitle == '提醒') {
					that.openBaseScreen('模具')
				} else if (that.modaltitle == '提示') {
					var initData = JSON.parse(JSON.stringify(this.$store.state.GuyueModule.ModuleData_select));
					parentData = initData[initData.length - 1]
					that.$refs.framework.ToLevel(parentData)
				}
			},
			getList() {
				var that = this
				that.Request.request('ZS_UpDownMoldList', {
					TypeName: '上模'
				}, function(res) {
					res.data.ds.map((item) => {
						item.Result = item.Result ? item.Result : 0
					})
					that.tableData = res.data.ds
				})
			},
			AddProductName() {
				var that = this;
				if (that.ButtonShow == true) {
					if (that.ProductNameList.length > 0) {
						that.ProductNameShow = true
					} else {
						that.showModal('提示', '该模具目前没有产品');
					}
				}
			},
			ProductNameClick(e) {
				var that = this;
				const formDefaults = {
					MoldID: e.MoludID,
					MoldNO: e.MoludCode
				};
				that.assignFormData(that.baseFormData, formDefaults)
				that.ProductNameShow = false
			},
			getValue(payload) {
				var that = this;
				that.showMLoading = false
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'人员': () => ({
						empolorName: data.UserName,
						empolorID: data.empolorID
					}),
					'模具': () => ({
						MoldID: data.MoludID,
						MoldNO: data.MoludCode
					}),
					'库位': () => ({
						FStorageID: data.FStorageID,
						FStorageName: data.FStorageName
					})
				};
				if (typeHandlers[type]) {
					Object.assign(this.baseFormData, typeHandlers[type]());
				}
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},
			getZS_getSMoldID(str) {
				var that = this
				console.log('ssss');
				that.Request.request('ZS_getSMoldIDByJobOrderID', {
					JobOrderID: that.baseFormData.JobOrderID,
					EquipmentID: that.baseFormData.EquipmentID
				}, function(res) {
					console.log(res);

					that.Request.request('getMoldByProductID', {
						ProductID: that.baseFormData.ProductID,
					}, function(ret) {
						if (ret.data.ds.length) {
							const {
								ds
							} = ret.data;
							const processedData = ds.map(item => ({
								...item,
								name: item.MoludCode
							}));
							that.MoludList = processedData;
							that.ProductNameList = processedData;
							const handleLoading = (state) => that.showMLoading = state;
							switch (ds.length) {
								case 1:
									const [firstItem] = ds;
									const {
										FStorageID, FStorageName, MoludID, MoludCode
									} = firstItem; // 解构常用属性																			
									const formDefaults = {
										MoldID: MoludID,
										MoldNO: MoludCode
									};
									that.assignFormData(that.baseFormData, formDefaults);
									if (FStorageID) {
										handleLoading(false);
										const formDefaults = {
											FStorageID: FStorageID,
											FStorageName: FStorageName
										};
										that.assignFormData(that.baseFormData, formDefaults);
									} else {
										that.loadingName = '正在获取数据中……';
										that.openBaseScreen('库位');
									}
									break;
								case 0:
									handleLoading(false);
									that.showModal('提醒', '该产品尚未配置相关的模具');
									break;
								default:
									handleLoading(false);
									that.AddProductName();
									that.ProductNameselect = true;
							}
						}
					})


				})
			},
			openBaseScreen(str) {
				var that = this;
				var obj;
				if (that.ButtonShow == true) {
					if (str == '人员') {
						obj = {
							cmd: 'getEmplByJobName',
							type: str,
							serverSearch: {
								isPaging: true, //是否分页
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
								searchShow: false, //是否查询
								searchKey: 'searchKey', //搜索关键词，应包含在param中
								showText: 'UserName', //查询结果显示的字段
							},
							param: {
								JobName: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					} else if (str == '模具') {

						obj = {
							cmd: 'ZS_Droplist_Molud',
							type: str,
							serverSearch: {
								isPaging: true, //是否分页
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
								searchShow: false, //是否查询
								searchKey: 'searchKey', //搜索关键词，应包含在param中
								showText: 'MoludCode', //查询结果显示的字段
							},
							param: {
								MoludID: 0,
								FWorkshopID: that.FWorkshopID,
								MoludCode: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					} else if (str == '库位') {

						if (that.baseFormData.FStorageName) {
							return
						}
						obj = {
							cmd: 'MJ_StorageList',
							type: str,
							serverSearch: {
								isPaging: true, //是否分页
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
								searchShow: true, //是否查询
								searchKey: 'FStorageName', //搜索关键词，应包含在param中
								showText: 'FStorageName', //查询结果显示的字段
								arrayList: 'ds1'
							},
							param: {
								MoludID: that.baseFormData.MoldID,
								FStorageID: 0,
								FStorageName: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					}

					uni.navigateTo({
						url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
						animationType: 'slide-in-right',
						animationDuration: 300
					});
				}

			},
			submit() {
				var that = this
				var msg
				var show = true
				var parentData
				var initData = JSON.parse(JSON.stringify(this.$store.state.GuyueModule.ModuleData_select));

				if (that.baseFormData.MoldNO == '' || that.baseFormData.MoldNO == null) {
					msg = '请选择模具'
					show = false
				} else if (that.baseFormData.ProductID == '' || that.baseFormData.ProductID == null) {
					msg = '请选择产品'
					show = false
				} else if (that.baseFormData.EquipmentName == '' || that.baseFormData.EquipmentName == null) {
					msg = '请选择设备'
					show = false
				}
				if (show) {
					var obj = {
						EndTime: getFormatDate(new Date()),
						JobOrderID: that.baseFormData.JobOrderID,
						Result: that.tableData.map(item => item.Result).join(','),
						EquipmentName: that.baseFormData.EquipmentName,
						StartTime: that.baseFormData.StartTime,
						empolorName: that.baseFormData.empolorName,
						MoludID: that.baseFormData.MoldID,
						ProductID: that.baseFormData.ProductID,
						empolorID: that.baseFormData.empolorID,
						EquipmentID: that.baseFormData.EquipmentID,
						MoldNO: that.baseFormData.MoldNO,
						FStorageID: that.baseFormData.FStorageID,
						MoldParameter: that.MoldParameter,
						WhiteORNight: 0,
						ZS_InspectionListID: that.tableData.map(item => item.ZS_InspectionListID).join(',')
					}
					console.log(obj);
					that.Request.request('ZS_UpMold', obj, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: ret.data.ds[0].msg
							})
							parentData = initData[initData.length - 1]
							that.$refs.framework.ToLevel(parentData)
						} else {
							that.showModal('报错', ret.data.ds[0].msg);
						}
					})
				} else {
					that.showModal('报错', msg);
				}
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getZSChangeMoldDetail', {
						ZSChangeMoldID: id
					}, function(ret) {
						that.showMLoading = false
						console.log(ret);
						that.ButtonShow = false

						const [firstItem] = ret.data.ds;
						// that.baseFormData = firstItem
						const formDefaults = {
							...firstItem,
							StartTime: formatDateTime(firstItem.StartTime),
							EquipmentName: firstItem.EquipmentCode ?? '',
							empolorName: firstItem.EmpolorName ?? ''
						};
						that.assignFormData(that.baseFormData, formDefaults)
						that.tableData = ret.data.ds1.map(e => ({
							...e,
							Result: e.Result === false ? 0 : 1
						})) || [];
					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					that.showMLoading = false
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},

			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},
		}
	}
</script>

<style lang="scss" >
	@import "../css/index.css";
</style>